package captcha

import (
	"gitee.com/pearl-zz/go-manage-system-core/storage"
	"github.com/mojocn/base64Captcha"
)

type cacheStore struct {
	cache      storage.AdapterCache
	expiration int
}

// NewCacheStore 实例化 returns a new standard memory store for captcha with the given collection threshold and expiration time.
// The returned store must be registered with SetCustomStore to replace the default one.
func NewCacheStore(cache storage.AdapterCache, expiration int) base64Captcha.Store {
	s := new(cacheStore)
	s.cache = cache
	s.expiration = expiration
	return s
}

func (e *cacheStore) Set(key string, value string) {
	_ = e.cache.Set(key, value, e.expiration)
}

func (e *cacheStore) Get(key string, clear bool) string {
	v, err := e.cache.Get(key)
	if err == nil {
		if clear {
			_ = e.cache.Del(key)
		}
		return v
	}
	return ""
}

func (e *cacheStore) Verify(key, answer string, clear bool) bool {
	return e.Get(key, clear) == answer
}
